/*
 * @Author: youngqj youngqj@126.com
 * @Date: 2024-11-02 17:17:48
 * @LastEditors: youngqj youngqj@126.com
 * @LastEditTime: 2024-12-03 18:54:55
 * @Description:
 *
 * Copyright © Zhejiang Xiaoqu Information Technology Co., Ltd, All Rights Reserved.
 */
package handler

import (
	"strconv"

	"xiaoquio/web/app/service"
	"xiaoquio/web/core/utils"

	"github.com/gin-gonic/gin"
)

type MemberHandler struct {
	service *service.MemberService
}

// 通过构造函数，注入服务
func NewMemberHandler(service *service.MemberService) *MemberHandler {
	return &MemberHandler{service: service}
}

// 获取用户信息，只有登录后才能访问
func (h *MemberHandler) GetUserInfo(c *gin.Context) {
	id := c.Param("id")
	userID, err := utils.Decrypt(id)
	if err != nil {
		utils.ResponseNilData(c, 500, "user id 解密失败")
		return
	}
	memberInfo, err := h.service.GetMemberInfoByID(c, userID)
	if err != nil {
		utils.ResponseNilData(c, 500, "用户不存在")
		return
	}

	utils.ResponseWithData(c, memberInfo, "获取数据成功！")
	return

}

func (h *MemberHandler) FindAllMembers(c *gin.Context) {
	pageStr := c.DefaultQuery("page", "1") //默认页码为1
	pageSizeStr := c.Query("page_size")    //默认分页数量

	if len(pageStr) == 0 || pageStr == "" {
		pageStr = "1" // 如果没有传值，则使用默认值
	}

	// 判断 pageSizeStr 是否为空
	if len(pageSizeStr) == 0 || pageSizeStr == "" {
		pageSizeStr = "20" // 如果没有传值，则使用默认值
	}

	page, err := strconv.Atoi(pageStr)
	if err != nil || page <= 0 {
		page = 1 // 如果转换失败，则使用默认值 1
	}

	pageSize, err := strconv.Atoi(pageSizeStr)
	if err != nil || pageSize <= 0 {
		pageSize = 10 // 如果转换失败，则使用默认值 10
	}

	members, total, err := h.service.FindAllMembers(c, page, pageSize)
	if err != nil {
		utils.ResponseNilData(c, 500, "数据查询失败！")
		return
	}
	//pages := (total / int64(pageSize))
	utils.ResponseWithPageInfo(c, members, "获取数据成功！", int(total), int(page), pageSize)

}
